import { reqGetCode,reqUserRegister,reqUserLogin,reqUserInfo,reqLogOut } from '@/api'

const state = {
    code:'',
    token: localStorage.getItem('token'),
    userInfo:{} 
};
const mutations = {
    GETCODE(state,code){
        state.code = code
    },
    USERLOGIN(state,token){
        state.token = token
    },
    GETUSERINFO(state,userInfo){
        state.userInfo = userInfo
    },
    CLEAR(state){
        state.token='';
        state.userInfo={};
        localStorage.removeItem("token")
    }

};
const actions = {
    async getCode({commit}, phone) {
        let result = await reqGetCode(phone)
        
        if(result.code == 200){
            commit('GETCODE',result.data)
        }
    },
  async  userRegister({ commit },user){
     let result =  await reqUserRegister(user)
     if(result.code ==200){
         return 'ok';
     }
    },
    async userLogin({commit},data){
        let result = await reqUserLogin(data)
        if(result.code == 200){
            commit("USERLOGIN",result.data.token);
            localStorage.setItem('token',result.data.token)
            return 'ok'
        }else{
            return Promise.reject(new Error('用户名和密码错误'))
        }
    },
   async getUserInfo({commit}){
      let result = await reqUserInfo();
     
      if(result.code == 200){
          commit ("GETUSERINFO",result.data)
          return 'ok'
      }
    },
   async userLoginOut({commit}){
        let result = await reqLogOut();
        
        if(result.code == 200){
            
            commit('CLEAR');
            return 'ok'
        }
    }
};
const getters = {
     
};

export default {
    // namespaced: true,
    // name: 'user',
    state,
    mutations,
    actions,
    getters
}